//
//  LoginSuccessViewController.swift
//  placepic
//
//  Created by elesahich on 2020/09/06.
//  Copyright © 2020 elesahich. All rights reserved.
//

import UIKit

class LoginSuccessViewController: UIViewController {
    
    var constraints: [NSLayoutConstraint] = []
    @IBOutlet weak var emptyView: UIView!
    
    let statusBar: UIView = {
        let view = UIView()
        view.frame = CGRect.zero
        view.backgroundColor = UIColor.blueGray50
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavigationBar()
        makeInitialProgressBar()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        DispatchQueue.main.asyncAfter(deadline: .now(),
                                      execute: {
                                        self.animateStatusBar()
        })
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        UIView.animate(withDuration: 5, animations: {
             self.createParticles()
         })
    }
}

extension LoginSuccessViewController {
    
//    safeArea Height를 구해야겠넹
    func makeInitialProgressBar() {
        self.view.addSubview(statusBar)
        
        constraints = [
            statusBar.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant:  0),
            statusBar.topAnchor.constraint(equalTo: emptyView.topAnchor, constant: 0),
            statusBar.heightAnchor.constraint(equalToConstant: 1.5),
            statusBar.widthAnchor.constraint(equalToConstant: self.view.frame.width / 2 + 20)
        ]
        NSLayoutConstraint.activate(constraints)
    }
    
    func animateStatusBar() {

        NSLayoutConstraint.deactivate(constraints)
        
        constraints = [
            statusBar.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant:  0),
            statusBar.bottomAnchor.constraint(equalTo: emptyView.topAnchor, constant: 0),
            statusBar.heightAnchor.constraint(equalToConstant: 1.5),
            statusBar.widthAnchor.constraint(equalToConstant: view.frame.width - 10)
            
        ]
        NSLayoutConstraint.activate(constraints)
        
        UIView.animate(withDuration: 1.5,
                       delay: 0.1,
                       usingSpringWithDamping: 1,
                       initialSpringVelocity: 1,
                       options: .curveEaseOut,
                       animations: {
                        self.view.layoutIfNeeded()
        }, completion: { (_) in
            let sb = UIStoryboard.init(name: "Tabbar", bundle: nil)
            guard let vc = sb.instantiateViewController(withIdentifier: "TabbarController") as? UITabBarController else { return }
            vc.modalPresentationStyle = .fullScreen
            let tempToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZHgiOjg1LCJuYW1lIjoi7J207Iq57Zi4IiwiaWF0IjoxNTk4MDg4MDUxLCJleHAiOjE2MDA2ODAwNTEsImlzcyI6InBsYWNlcGljIn0.JFUQDERVUsOlO3YEVJIfIg5sRxZ1204EuPDydmgyYSQ"
            UserDefaults.standard.set(tempToken, forKey: "accessToken")
            
            self.present(vc, animated: true)
        })
    }
    
    
    private func setupNavigationBar() {
        guard let navigationBar = self.navigationController?.navigationBar else { return }
        
        navigationBar.isTranslucent = true
        navigationBar.backgroundColor = UIColor.clear
        navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        navigationBar.shadowImage = UIImage()
        
        let title: UILabel = {
            let label = UILabel()
            label.text = ""
            label.font = .boldSystemFont(ofSize: 18)
            label.textColor = UIColor.gray90
            return label
        }()
        
        let backButton: UIButton = {
            let bt = UIButton()
            bt.setImage(UIImage(named: ""), for: .normal)
            return bt
        }()
        
        backButton.addTarget(self,
                             action: #selector(dismissVC),
                             for: .touchUpInside)
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
        navigationItem.titleView = title
    }
    
    @objc
    private func dismissVC() {
        self.navigationController?.popViewController(animated: true)
    }
}

extension LoginSuccessViewController {
    
    private func getRandomVelocity() -> Int {
        return velocities[getRandomNumber()]
    }
    
    private func getRandomNumber() -> Int {
        return Int(arc4random_uniform(4))
    }
    
    private func getNextColor(i:Int) -> CGColor {
        if i <= 4 {
            return colors[0].cgColor
        } else if i <= 8 {
            return colors[1].cgColor
        } else if i <= 12 {
            return colors[2].cgColor
        } else {
            return colors[3].cgColor
        }
    }
    
    private func getNextImage(i:Int) -> CGImage {
        return images[i % 4].cgImage!
    }
    
    private func createParticles() {
        let emitter = CAEmitterLayer()
        emitter.emitterPosition = CGPoint(x: self.view.frame.size.width / 2, y: -10)
        emitter.emitterShape = CAEmitterLayerEmitterShape.line
        emitter.emitterSize = CGSize(width: self.view.frame.size.width, height: 2.0)
        emitter.emitterCells = generateEmitterCells()
        
        if let window = UIApplication.shared.windows.first(where: { $0.isKeyWindow }) {
            let view = UIView()
            view.frame = window.frame
            window.layer.addSublayer(emitter)
            let time = DispatchTime.now() + .seconds(3)
            DispatchQueue.main.asyncAfter(deadline: time, execute: {
                emitter.birthRate = 0
            })
        }
    }
    
    private func generateEmitterCells() -> [CAEmitterCell] {
        var cells: [CAEmitterCell] = [CAEmitterCell]()
        for index in 0..<16 {
            let cell = CAEmitterCell()
            cell.birthRate = 3.0
            cell.lifetime = 14.0
            cell.lifetimeRange = 0
            cell.velocity = CGFloat(getRandomVelocity())
            cell.velocityRange = 0
            cell.emissionLongitude = CGFloat(Double.pi)
            cell.emissionRange = 0.5
            cell.spin = 3.5
            cell.spinRange = 0
            cell.color = getNextColor(i: index)
            cell.contents = getNextImage(i: index)
            cell.scaleRange = 0.25
            cell.scale = 0.1
            cells.append(cell)
        }
        return cells
    }
}

enum Images {
    static let box = UIImage(named: "Box")!
    static let triangle = UIImage(named: "Triangle")!
    static let circle = UIImage(named: "Circle")!
    static let swirl = UIImage(named: "Spiral")!
}


var colors: [UIColor] = [
    Colors.red,
    Colors.blue,
    Colors.green,
    Colors.yellow
]

var images: [UIImage] = [
    Images.box,
    Images.triangle,
    Images.circle,
    Images.swirl
]

var velocities: [Int] = [
    100,
    90,
    250,
    400
]

enum Colors {
    
    static let red = UIColor(red: 1.0, green: 0.0, blue: 77.0/255.0, alpha: 1.0)
    static let blue = UIColor(red: 72/255, green: 144/255, blue: 218/255, alpha: 1)
    static let green = UIColor(red: 35.0/255.0 , green: 233/255, blue: 173/255.0, alpha: 1.0)
    static let yellow = UIColor(red: 1, green: 209/255, blue: 77.0/255.0, alpha: 1.0)

}
